import React, { useEffect, useState } from 'react';
import { Button, message, Popconfirm, Space, Table, Row, Col, Modal, Form, Input, DatePicker, Select, Upload } from 'antd';
import { DeleteOutlined, EditOutlined, EyeOutlined, PlusOutlined, SearchOutlined, SyncOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useNavigate } from 'react-router-dom';
import ReimburseService from '../../services/ReimburseService';
import '../components.css';

const { Option } = Select;

export default function ReimburseManagement() {
  const [reimburses, setReimburses] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectAll, setSelectAll] = useState(false);
  const [reimburseDetail, setReimburseDetail] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [importLoading, setImportLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);

  const getAllReimburses = (params = {}) => {
    setLoading(true);
    ReimburseService.getAllReimburses(params)
      .then((response) => {
        console.log("API Response:", response);
        if (response && Array.isArray(response)) {
          setReimburses(response);
        } else {
          message.warning("返回的数据格式不正确");
          setReimburses([]);
        }
        setLoading(false);
      })
      .catch(error => {
        console.error("API Error:", error);
        message.error("获取报销数据失败");
        setLoading(false);
      });
  };

  // 导入处理函数
  const handleImport = (info) => {
    setImportLoading(true);
    
    ReimburseService.importReimburses(info.file)
      .then(response => {
        if (response.data === "导入成功") {
          message.success('导入成功！');
          getAllReimburses();
        } else {
          message.error('导入失败: ' + response.data);
        }
      })
      .catch(error => {
        message.error('导入失败: ' + (error.response?.data || error.message));
      })
      .finally(() => {
        setImportLoading(false);
      });
  };

  // 导出处理函数
  const handleExport = () => {
    setExportLoading(true);
    const params = form.getFieldsValue();
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    );
    
    ReimburseService.exportReimburses(filteredParams)
      .then(response => {
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `reimburses_${moment().format('YYYYMMDDHHmmss')}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('导出成功！');
      })
      .catch(error => {
        message.error('导出失败: ' + (error.response?.data || error.message));
      })
      .finally(() => {
        setExportLoading(false);
      });
  };

  useEffect(() => {
    getAllReimburses();
  }, []);

  const onSelectChange = (selectedKeys) => {
    setSelectedRowKeys(selectedKeys);
    setSelectAll(selectedKeys.length === reimburses.length && reimburses.length > 0);
  };

  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedRowKeys([]);
    } else {
      setSelectedRowKeys(reimburses.map(reimburse => reimburse.id));
    }
    setSelectAll(!selectAll);
  };

  const handleInvertSelection = () => {
    const invertedSelection = reimburses
      .map(reimburse => reimburse.id)
      .filter(id => !selectedRowKeys.includes(id));
    setSelectedRowKeys(invertedSelection);
    setSelectAll(false);
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一项');
      return;
    }
    
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的${selectedRowKeys.length}条报销记录吗？`,
      onOk: () => {
        Promise.all(selectedRowKeys.map(id => ReimburseService.deleteReimburse(id)))
          .then(() => {
            message.success('删除成功');
            getAllReimburses();
            setSelectedRowKeys([]);
            setSelectAll(false);
          })
          .catch(error => {
            console.log(error);
            message.error('删除失败');
          });
      }
    });
  };

  const deleteReimburse = (id) => {
    ReimburseService.deleteReimburse(id)
      .then(() => {
        message.success('删除成功');
        getAllReimburses();
      })
      .catch(error => {
        console.log(error);
        message.error('删除失败');
      });
  };

  const handleShowDetail = (record) => {
    setReimburseDetail(record);
    setDetailModalVisible(true);
  };

  const handleAddReimburse = () => {
    navigate('/reimburses/add');
  };

  const handleEditReimburse = (id) => {
    navigate(`/reimburses/edit/${id}`);
  };

  const onFinish = (values) => {
    const params = {
      reimburseName: values.reimburseName,
      reimburseDepartment: values.reimburseDepartment,
      reimburseDate: values.reimburseDate ? values.reimburseDate.toDate() : undefined,
      reimburseState: values.reimburseState
    };
    
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    );
    getAllReimburses(filteredParams);
  };

  const onReset = () => {
    form.resetFields();
    getAllReimburses();
  };

  const columns = [
    {
      title: '选择',
      key: 'selection',
      align: 'center',
      width: 60,
      render: (_, record) => (
        <input
          type="checkbox"
          checked={selectedRowKeys.includes(record.id)}
          onChange={() => {
            const newSelectedRowKeys = selectedRowKeys.includes(record.id)
              ? selectedRowKeys.filter(key => key !== record.id)
              : [...selectedRowKeys, record.id];
            onSelectChange(newSelectedRowKeys);
          }}
        />
      ),
    },
    {
      title: '报销编号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '报销名称',
      dataIndex: 'reimburseName',
      key: 'reimburseName',
      align: 'center',
      sorter: (a, b) => a.reimburseName.localeCompare(b.reimburseName),
    },
    {
      title: '报销部门',
      dataIndex: 'reimburseDepartment',
      key: 'reimburseDepartment',
      align: 'center',
      sorter: (a, b) => a.reimburseDepartment.localeCompare(b.reimburseDepartment),
    },
    {
      title: '报销金额',
      dataIndex: 'reimbursePrice',
      key: 'reimbursePrice',
      align: 'center',
      render: (text) => `¥${text.toFixed(2)}`,
      sorter: (a, b) => a.reimbursePrice - b.reimbursePrice,
    },
    {
      title: '报销日期',
      dataIndex: 'reimburseDate',
      key: 'reimburseDate',
      align: 'center',
      render: (date) => date ? moment(date).format('YYYY-MM-DD') : '-',
      sorter: (a, b) => new Date(a.reimburseDate) - new Date(b.reimburseDate),
    },
    {
      title: '报销状态',
      dataIndex: 'reimburseState',
      key: 'reimburseState',
      align: 'center',
      sorter: (a, b) => a.reimburseState.localeCompare(b.reimburseState),
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EyeOutlined />}
            onClick={() => handleShowDetail(record)}
          >
            详情
          </Button>
          
          <Popconfirm
            title="确定删除这条报销记录吗?"
            onConfirm={() => deleteReimburse(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="danger" icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className='reimburse-management'>
      <div className="title">报销管理</div>
      
      {/* Search Form */}
      <Form
        form={form}
        layout="inline"
        onFinish={onFinish}
        style={{
          marginBottom: 20,
          background: '#fafafa',
          padding: 20,
          borderRadius: 4,
          display: 'flex',
          alignItems: 'center'
        }}
      >
        <div style={{ flex: 1, display: 'flex', gap: 16 }}>
          <Form.Item name="reimburseName" style={{ flex: 1 }}>
            <Input placeholder="报销名称" allowClear />
          </Form.Item>
          <Form.Item name="reimburseDepartment" style={{ flex: 1 }}>
            <Input placeholder="报销部门" allowClear />
          </Form.Item>
          <Form.Item name="reimburseDate" style={{ flex: 1 }}>
            <DatePicker style={{ width: '100%' }} placeholder="报销日期" format="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="reimburseState" style={{ flex: 1 }}>
            <Select placeholder="报销状态" style={{ width: '100%' }} allowClear>
              <Option value="已通过">已通过</Option>
              <Option value="待审批">待审批</Option>
              <Option value="被否决">被否决</Option>
              <Option value="被驳回">被驳回</Option>
              <Option value="已撤销">已撤销</Option>
            </Select>
          </Form.Item>
        </div>
        
        <Form.Item style={{ marginLeft: 'auto' }}>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={onReset} icon={<SyncOutlined />}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Row justify="space-between" style={{ marginBottom: 16 }}>
        <Col>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddReimburse}
            >
              添加
            </Button>
            
            {/* 导入按钮 */}
            <Upload
              accept=".csv"
              showUploadList={false}
              customRequest={handleImport}
              beforeUpload={(file) => {
                const isCsv = file.type === 'text/csv' || file.name.endsWith('.csv');
                if (!isCsv) {
                  message.error('只能上传CSV文件!');
                }
                return isCsv;
              }}
            >
              <Button
                type="primary"
                icon={<UploadOutlined />}
                loading={importLoading}
              >
                导入
              </Button>
            </Upload>
            
            {/* 导出按钮 */}
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
              loading={exportLoading}
            >
              导出
            </Button>
          </Space>
        </Col>
        <Col>
          <Space>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={() => message.info('排序功能待实现')}
            >
              排序
            </Button>
            <Button
              type="primary"
              icon={<EyeOutlined />}
              onClick={() => message.info('列表视图切换功能待实现')}
            >
              列表
            </Button>
          </Space>
        </Col>
      </Row>

      <Table 
        columns={columns} 
        dataSource={reimburses} 
        bordered={true} 
        loading={loading}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      
      <div style={{ marginTop: 16 }}>
        <Space>
          <Button
            type="primary"
            onClick={handleSelectAll}
          >
            {selectAll ? '取消全选' : '全选'}
          </Button>
          <Button
            type="primary"
            onClick={handleInvertSelection}
          >
            反选
          </Button>
          <Popconfirm
            title="确定删除选中的报销记录吗?"
            onConfirm={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            <Button
              type="primary"
              icon={<DeleteOutlined />}
              danger
              disabled={selectedRowKeys.length === 0}
            >
              批量删除 ({selectedRowKeys.length})
            </Button>
          </Popconfirm>
        </Space>
      </div>

      {/* Detail Modal */}
      <Modal
        title="报销详情"
        visible={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="back" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          
        ]}
        width={800}
      >
        {reimburseDetail && (
          <div>
            <div style={{ marginBottom: 16, fontWeight: 'bold' }}>基本信息</div>
            
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销编号：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{reimburseDetail.id}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销名称：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{reimburseDetail.reimburseName}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销金额：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>¥{reimburseDetail.reimbursePrice?.toFixed(2)}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销部门：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{reimburseDetail.reimburseDepartment}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销日期：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>
                    {reimburseDetail.reimburseDate ? moment(reimburseDetail.reimburseDate).format('YYYY-MM-DD') : '-'}
                  </td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销状态：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{reimburseDetail.reimburseState}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>备注：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>
                    {reimburseDetail.reimburseNote || '-'}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
      </Modal>
    </div>
  );
}